package edu.jmu.myshop.service.reg.controller;

import edu.jmu.myshop.commons.domain.TbUser;
import edu.jmu.myshop.commons.dto.AbstractBaseResult;
import edu.jmu.myshop.commons.dto.BaseResultFactory;
import edu.jmu.myshop.commons.mapper.TbUserMapper;
import edu.jmu.myshop.commons.service.TbUserService;
import edu.jmu.myshop.commons.validator.BeanValidator;
import edu.jmu.myshop.commons.web.AbstractBaseController;
import edu.jmu.myshop.service.reg.service.RegService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * @author Wen
 */

@RestController
@RequestMapping(value = "reg")
public class RegController extends AbstractBaseController<TbUser> {

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private RegService regService;


    @ApiOperation(value = "用户注册", notes = "参数为实体类TbUser，注意用户名、邮箱不能重复")
    @PostMapping(value = "user")
    public AbstractBaseResult reg(@ApiParam(name = "tbUser", value = "用户模型") TbUser tbUser) {

        String message = BeanValidator.validator(tbUser);
        if (StringUtils.isNotBlank(message)) {
            return error(HttpStatus.UNAUTHORIZED.value(), message, null);

        }

        // 验证用户名是否重复
        if (!tbUserService.unique("username", tbUser.getUsername())) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return error(HttpStatus.UNAUTHORIZED.value(), "用户名重复请重试", null);
        }

        // 验证邮箱是否重复
        if (!tbUserService.unique("email", tbUser.getEmail())) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return error(HttpStatus.UNAUTHORIZED.value(), "邮箱重复请重试", null);
        }

        tbUser.setPassword(DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes(StandardCharsets.UTF_8)));
        TbUser user = tbUserService.save(tbUser);
        if (user != null) {
            regService.sendEmail(user);
            response.setStatus(HttpStatus.CREATED.value());
            return success(user);
        }
        return error(HttpStatus.UNAUTHORIZED.value(), "注册失败，请重试", null);
    }
}
